package com.kuaimacode.kframework.service;

import com.alibaba.fastjson.JSONObject;
import com.kuaimacode.kframework.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-07-18 15:39
 */
@Slf4j
@Service
public class WeixinTokenService {

    @Value("${weixin.applets.appId}")
    private String appId;
    @Value("${weixin.applets.appSecret}")
    private String appSecret;
    private static volatile String token = null;
    private static volatile long expireTime = 0;

    public String getToken() throws Exception {
        if (token != null && expireTime > System.currentTimeMillis()/1000) {
            return token;
        }

        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", appId);
        params.put("secret", appSecret);
        String response = HttpUtil.getString("https://api.weixin.qq.com/cgi-bin/token", params);
        log.info("get wechat token response: [{}]", response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getIntValue("errcode") == 0) {
            token = jsonObject.getString("access_token");
            expireTime = jsonObject.getLongValue("expires_in");
            return token;
        }
        log.error("get wechat token error", response);
        return "";
    }
}
